from utils import file
from lib.server.http.fs import net_fs
from lib.server.http import response,api

async def visit_root(writer, path):
    """访问根目录"""
    # print(f"visit {path}")
    index_path = "/index.html"
    real_path = net_fs.real_path(index_path)
    if file.is_file(real_path):
        await visit_file(writer, index_path)
        return
    response_str = f"HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhello world"
    writer.write(response_str)


async def visit_file(writer, path):
    """访问vfs文件"""
    (info, data) = net_fs.read(path)
    size = info["size"]

    if size <= 0 or data is None:
        return await response.return_json_error(writer)

    header = response.create_headers(info)
    # print(header)
    res = bytearray(bytes(header, "ascii"))

    # 超过设置大小
    if size > 0 and size > net_fs.get_max_file_size():
        writer.write(res)
        await net_fs.write_chunk(writer, path)
        return

    res.extend(data)
    writer.write(res)

async def visit_log(writer, path):
    """访问vfs文件"""
    log_file_path = f"{path}"
    (info, data) = net_fs.read_file(log_file_path)
    size = info["size"]

    if size <= 0 or data is None:
        return await response.return_json_error(writer)

    header = response.create_headers(info)
    # print(header)
    res = bytearray(bytes(header, "ascii"))

    # 超过设置大小
    if size > 0 and size > net_fs.get_max_file_size():
        writer.write(res)
        await net_fs.write_chunk(writer, path)
        return

    res.extend(data)
    writer.write(res)


async def visit_api(writer, path):
    """访问api"""
    await api.handle_api_routes(writer, path)

